package com.atguigu.gmall.pms.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import org.apache.commons.codec.language.Nysiis;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.CategoryMapper;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import com.atguigu.gmall.pms.service.CategoryService;
import org.springframework.util.CollectionUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryMapper  categoryMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "pms:cates:";

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<CategoryEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public List<CategoryEntity> categoryByPid(Long pid) {
        QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
        if (pid!=-1){
            //根据pid查询一级分类的所有下级分类
            queryWrapper.eq("parent_id", pid);
        }
        //pid = -1 查询所有三级分类
        return this.list(queryWrapper);
    }

    @Override
    public List<CategoryEntity> categoriesWithSubsByPid(Long pid) {
        // 查询 Redis 缓存
        String json = this.redisTemplate.opsForValue().get(KEY_PREFIX + pid);
        if (StringUtils.isNotBlank(json)){
            // 存在该数据  转换格式响应
            List<CategoryEntity> categoryEntities = JSON.parseArray(json, CategoryEntity.class);
            return categoryEntities;
        }
        // DB 查询
        List<CategoryEntity> categoryEntities = this.categoryMapper.categoriesWithSubsByPid(pid);
        // 设置Redis缓存
        if (CollectionUtils.isEmpty(categoryEntities)){
            // 缓存穿透 ,大量访问不存在的数据 设置null值 过期时间
            this.redisTemplate.opsForValue().set(KEY_PREFIX+pid, null, 5, TimeUnit.MINUTES);
        }else {
            // 为正常数据设置长过期时间
            // 为防止 缓存雪崩 大量数据同时过期 设置随机过期时间
            this.redisTemplate.opsForValue().set(KEY_PREFIX+pid, JSON.toJSONString(categoryEntities),30+new Random().nextInt(10),TimeUnit.DAYS);
        }

        return categoryEntities;

    }

    /**
     * 根据三级分类id 查询一二三级分类
     * @param id
     * @return
     */
    @Override
    public List<CategoryEntity> categories123ByCid3(Long id) {

        CategoryEntity entityLevel3 = this.getById(id);
        if (entityLevel3==null){
            return null;
        }
        // 查询二级分类
        CategoryEntity entityLevel2 = this.getById(entityLevel3.getParentId());

        // 查询一级分类
        CategoryEntity entityLevel1 = this.getById(entityLevel2.getParentId());

        return Arrays.asList(entityLevel1,entityLevel2,entityLevel3);
    }

}